//
//  BoxManagementView.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import SwiftUI

struct BoxManagementView: View {
    @EnvironmentObject var boxManager: BoxManager
    @State private var showingAddBox = false
    @State private var showingRenameBox: Box? = nil
    @State private var newBoxName = ""
    @State private var errorMessage: String? = nil
    @State private var showingError = false
    
    var body: some View {
        NavigationView {
            List {
                Section(header: Text("我的盒子")) {
                    ForEach(boxManager.getAllBoxes()) { box in
                        BoxRow(box: box, 
                              onRename: { showingRenameBox = box },
                              onDelete: { tryDeleteBox(box) })
                    }
                }
                
                Section {
                    Button(action: { showingAddBox = true }) {
                        HStack {
                            Image(systemName: "plus.circle.fill")
                            Text("添加新盒子")
                        }
                        .foregroundColor(.blue)
                    }
                }
            }
            .navigationTitle("盒子管理")
            .sheet(isPresented: $showingAddBox) {
                AddBoxView(isPresented: $showingAddBox, 
                          boxName: $newBoxName,
                          onAdd: addNewBox)
            }
            .sheet(item: $showingRenameBox) { box in
                RenameBoxView(box: box, 
                            isPresented: Binding(get: { showingRenameBox != nil }, 
                                                set: { if !$0 { showingRenameBox = nil } }),
                            onRename: renameBox)
            }
            .alert("错误", isPresented: $showingError, presenting: errorMessage) { _ in
                Button("确定", role: .cancel) {}
            } message: { message in
                Text(message)
            }
        }
    }
    
    private func addNewBox(name: String) {
        do {
            try boxManager.addBox(name: name)
            newBoxName = ""
        } catch {
            showError(error.localizedDescription)
        }
    }
    
    private func renameBox(box: Box, newName: String) {
        do {
            try boxManager.renameBox(boxId: box.id, newName: newName)
        } catch {
            showError(error.localizedDescription)
        }
    }
    
    private func tryDeleteBox(_ box: Box) {
        do {
            try boxManager.deleteBox(boxId: box.id)
        } catch {
            showError(error.localizedDescription)
        }
    }
    
    private func showError(_ message: String) {
        errorMessage = message
        showingError = true
    }
}

// 盒子行组件
struct BoxRow: View {
    let box: Box
    let onRename: () -> Void
    let onDelete: () -> Void
    
    var body: some View {
        HStack {
            // 盒子图标
            Image(systemName: "cube.fill")
                .font(.title2)
                .foregroundColor(box.isDefault ? .blue : .gray)
                .frame(width: 40, height: 40)
                .background(box.isDefault ? Color.blue.opacity(0.1) : Color.gray.opacity(0.1))
                .cornerRadius(8)
            
            VStack(alignment: .leading, spacing: 4) {
                Text(box.name)
                    .font(.headline)
                
                if box.isDefault {
                    Text("默认盒子")
                        .font(.caption)
                        .foregroundColor(.blue)
                }
                
                Text("创建于: \(formatDate(box.createdAt))")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            Spacer()
            
            // 操作菜单
            Menu {
                Button("重命名", action: onRename)
                
                if !box.isDefault {
                    Button("设为默认", role: .none) {
                        try? BoxManager.shared.setDefaultBox(boxId: box.id)
                    }
                    
                    Button("删除", role: .destructive, action: onDelete)
                }
            } label: {
                Image(systemName: "ellipsis")
                    .padding(8)
            }
        }
        .padding(.vertical, 4)
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
}

// 添加盒子视图
struct AddBoxView: View {
    @Binding var isPresented: Bool
    @Binding var boxName: String
    let onAdd: (String) -> Void
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("盒子名称")) {
                    TextField("请输入盒子名称", text: $boxName)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                }
                
                Section {
                    Button("添加") {
                        if !boxName.trimmingCharacters(in: .whitespaces).isEmpty {
                            onAdd(boxName.trimmingCharacters(in: .whitespaces))
                            isPresented = false
                        }
                    }
                    .disabled(boxName.trimmingCharacters(in: .whitespaces).isEmpty)
                }
            }
            .navigationTitle("添加盒子")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        isPresented = false
                    }
                }
            }
        }
    }
}

// 重命名盒子视图
struct RenameBoxView: View {
    let box: Box
    @Binding var isPresented: Bool
    @State private var newName: String
    let onRename: (Box, String) -> Void
    
    init(box: Box, isPresented: Binding<Bool>, onRename: @escaping (Box, String) -> Void) {
        self.box = box
        self._isPresented = isPresented
        self.onRename = onRename
        self._newName = State(initialValue: box.name)
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("盒子名称")) {
                    TextField("请输入新名称", text: $newName)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                }
                
                Section {
                    Button("保存") {
                        if !newName.trimmingCharacters(in: .whitespaces).isEmpty {
                            onRename(box, newName.trimmingCharacters(in: .whitespaces))
                            isPresented = false
                        }
                    }
                    .disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty || newName == box.name)
                }
            }
            .navigationTitle("重命名盒子")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        isPresented = false
                    }
                }
            }
        }
    }
}

#Preview {
    BoxManagementView()
        .environmentObject(BoxManager.shared)
}